from django import forms
from app01 import models


class BookForm(forms.Form):
    """书籍数据校验类"""
    title = forms.CharField(
        label='书名',
        max_length=64,
        error_messages={'required': '不能为空'},
    )
    pub_date = forms.CharField(
        label="出版日期",
        error_messages={'required': '不能为空'},
        widget=forms.TextInput(attrs={'type': 'date'}),
    )
    price = forms.DecimalField(
        label='价格',
        max_value=100,
        min_value=1,
        max_digits=4,
        decimal_places=2,
        error_messages={'required': '不能为空'},
    )
    pub = forms.ModelChoiceField(
        label="出版社",
        queryset=models.Publish.objects.all(),
        error_messages={'required': '不能为空'},
    )

    authors = forms.ModelMultipleChoiceField(
        label="作者",
        queryset=models.Author.objects.all(),
        error_messages={'required': '不能为空'},
    )

    # 想在自己定义的forms类在初始化的时候统一加一些样式
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            # print(name, field)
            field.widget.attrs.update({'class': 'form-control'})


'''
title = models.CharField(max_length=64, db_column='xx') #not null
pub_date = models.DateField()
price = models.DecimalField(max_digits=10,decimal_places=2)
pub = models.ForeignKey('Publish')
authors = models.ManyToManyField('Author')

'''


class BookModelForm(forms.ModelForm):
    # 可以自己来创建form属性，那么它会替换modelform帮我们自动生成的form属性
    title = forms.CharField(max_length=64, min_length=2)

    class Meta:
        model = models.Book
        fields = '__all__'
        # fields = ['title','price']  #指定model模型类中的属性，modelform只生成和校验这几个属性对应的form属性
        # exclude = ['title','price'] #排除指定属性

        # labels = {
        #     'title': '书籍名称',
        #     'pub': '出版社',
        #     'price': '价格',
        #     'pub_date': '出版日期',
        #     'authors': '作者',
        # }
        error_messages = {
            'title': {'required': '不能为空', 'max_length': '不能太长，受不了'},
            'price': {'required': '不能为空', },
        }
        widgets = {
            'pub_date': forms.TextInput(attrs={'type': "date"}),
            'title': forms.TextInput(attrs={'class': "c1"}),
        }

    # 想在自己定义的forms类在初始化的时候统一加一些样式
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        for name, field in self.fields.items():
            # print(name, field)
            field.widget.attrs.update({'class': 'form-control'})
